<script lang="ts" setup>
  import { onMounted, reactive, ref, computed } from 'vue'
  import { timeFormatUTC } from '@/utils/formatter'
  import MeDialog from '../dialog/index.vue'
  import MeSearch from '@/components/Search.vue'
  import { useRoute, useRouter } from 'vue-router'
  const route = useRoute()
  let searchArr: Array<{ [key: string]: string }> = reactive([])
  const emit = defineEmits(['fupdate'])
  let comingState = ref({} as { [key: string]: string })
  let startTime = ref('')
  let endTime = ref('')
  const props = defineProps({
    data: Array
  })
  const defaultTime = new Date(2023, 1, 1, 23, 59, 59)
  const startDisabled = (date: any) => {
    if (endTime.value) {
      let start = new Date(date).getTime()
      let end = new Date(endTime.value).getTime() + 24 * 60 * 60 * 1000 - 1
      return start >= end
    }
    return false
  }
  const endDisabled = (date: any) => {
    if (startTime.value) {
      let start = new Date(startTime.value).getTime()
      let end = new Date(date).getTime() + 24 * 60 * 60 * 1000 - 1
      return start >= end
    }
    return false
  }
  let searches: { [key: string]: string } = {}
  let monitor = {
    start_time: '',
    end_time: ''
  }
  const getSessions = async () => {
    let starttemp = startTime.value ? startTime.value : ''
    let endtemp = endTime.value ? endTime.value : ''
    if (endTime.value || startTime.value) {
      monitor.start_time = starttemp
      monitor.end_time = endtemp
    } else {
      monitor.start_time = ''
      monitor.end_time = ''
    }

    emit('fupdate', { ...monitor, ...searches })
  }
  const ys = {
    instance_id: '实例id',
    process_id: '进程id',
    ip_address: 'ip地址',
    state: '状态',
    server_session_id: '服务器会话id'
  }
  let searchData = computed(() => {
    return {
      inputSearch: {
        instance_id: { name: '实例id' },
        process_id: { name: '进程id' },
        ip_address: { name: 'ip地址' },
        server_session_id: { name: '服务器会话id' }
      },
      choseSearch: {
        state: {
          name: '状态',
          num: 0,
          data: [
            { value: 'ACTIVATING', text: 'ACTIVATING' },
            { value: 'ERROR', text: 'ERROR' },
            { value: 'ACTIVE', text: 'ACTIVE' },
            { value: 'TERMINATED', text: 'TERMINATED' }
          ]
        }
      }
    }
  })
  const setSearchArr = (arr: Array<{ [key: string]: string }>) => {
    searchArr.length = 0
    searchArr.push(...arr)
    let obj: { [key: string]: string } = {}
    searchArr.forEach((item) => {
      let temp_arr = item.value.split(';')
      let value_arr: (string | number)[] = []
      temp_arr.forEach((val) => {
        if (val === '是') {
          value_arr.push(1)
        } else if (val === '否') {
          value_arr.push(0)
        } else {
          value_arr.push(val)
        }
      })
      obj[item.key] = value_arr.join(';')
    })
    searches = obj
    emit('fupdate', { ...monitor, ...searches })
  }
  if (route.query.health_state && route.query.run == 'Session') {
    if (typeof route.query.health_state == 'string') {
      comingState.value = { key: 'state', value: route.query.health_state }
      setSearchArr([comingState.value])
    }
  }
  let showDialog = ref(false)
  let dialogData = reactive({})
  const dialogName = ref('会话')
  const showDetails = (row: any) => {
    dialogData = row
    showDialog.value = true
  }
  const closeDetails = () => {
    showDialog.value = false
  }
  const refresh = () => {
    searchArr.length = 0
    emit('fupdate')
  }
</script>
<template>
  <div class="table-sessions">
    <div class="refresh">
      <div class="search-box">
        <me-search :search="searchData" :ys="ys" :searchConArr="searchArr" @search="setSearchArr"></me-search>
      </div>
      <div class="dataRange">
        <span>筛选创建时间范围：</span>
        <el-date-picker
          v-model="startTime"
          type="datetime"
          placeholder="请输入开始时间"
          @change="getSessions"
          :disabled-date="startDisabled"
          format="YYYY/MM/DD HH:mm:ss"
          value-format="YYYY-MM-DDTHH:mm:ss"
        />
        <el-date-picker
          v-model="endTime"
          type="datetime"
          placeholder="请输入结束时间"
          @change="getSessions"
          :disabled-date="endDisabled"
          format="YYYY/MM/DD HH:mm:ss"
          value-format="YYYY-MM-DDTHH:mm:ss"
          :default-time="defaultTime"
        />
        <el-icon @click="refresh()" class="refreshIcon">
          <RefreshLeft />
        </el-icon>
      </div>
    </div>
    <div class="table-box">
      <el-table
        :data="props.data"
        style="width: 100%"
        :header-cell-style="{ background: '#fafafe', color: '#1d1d1f' }"
        :border="true"
        :default-sort="{ prop: 'creation_time', order: 'descending' }"
      >
        <el-table-column label="名称/ID">
          <template #default="scope">
            <div class="toDetails" @click="showDetails(scope.row)">
              {{ scope.row.name }}
            </div>
            <el-tooltip effect="dark" :content="scope.row.server_session_id" placement="bottom">
              <div class="id-box">
                {{ scope.row.server_session_id }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="实例ID/IP地址" width="260">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.instance_id" placement="bottom">
              <div class="id-box">
                {{ scope.row.instance_id }}
              </div>
            </el-tooltip>
            <div>
              {{ scope.row.ip_address }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="进程ID/端口" width="260">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.process_id" placement="bottom">
              <div class="id-box">
                {{ scope.row.process_id }}
              </div>
            </el-tooltip>
            <div>
              {{ scope.row.port }}
            </div>
          </template>
        </el-table-column>
        <el-table-column property="current_client_session_count" label="客户端会话数量" />
        <el-table-column property="state" label="状态">
          <template #default="scope">
            {{ scope.row.state ? $t(scope.row.state) : '' }}
          </template>
        </el-table-column>
        <el-table-column property="state_reason" label="状态原因" />
        <el-table-column property="created_time" label="创建时间" :formatter="timeFormatUTC" sortable />
      </el-table>
    </div>
    <transition name="dialog">
      <me-dialog :data="dialogData" v-if="showDialog" :title="dialogName" @close="closeDetails"></me-dialog>
    </transition>
  </div>
</template>
<style lang="scss" scoped>
  .dialog-enter-active {
    transition: all 0.3s ease;
  }

  .dialog-leave-active {
    transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
  }

  .dialog-enter,
  .dialog-leave-to {
    transform: translateX(10px);
    opacity: 0;
  }

  .table-box {
    border-radius: 2px;
    margin-top: 20px;
  }
  .search-box {
    width: 56%;
  }
  .refresh {
    display: flex;
    justify-content: space-between;
    .dataRange {
      display: flex;
      margin-left: 50px;
      align-items: center;
      gap: 5px;
      span {
        font-size: 14px;
      }
    }
    .refreshIcon {
      width: 28px;
      height: 28px;
    }
  }
</style>
